<template>
  <div class="salesSummary">
    <x-header class="header" :left-options="{showBack: showHeaderBack,preventGoBack:true}" @on-click-back="goToPage" ref="header">酒水销售汇总</x-header>
    <div class="topHolder"></div>
    <card class="gridDisplay">
      <div class="card-padding" slot="content" style="padding-top: 0;">
        <div class="filterArea dateFilter" ref="filterArea">
          <group-title style="text-align: center;">当前显示日期：{{choosenDate}}<br/></group-title>
          <x-button :show-loading="loadingStatus" :disabled="loadingStatus" @click.native="changeDate(1)" class="inlineBtn">今日</x-button>
          <x-button :show-loading="loadingStatus" :disabled="loadingStatus" @click.native="changeDate(2)" class="inlineBtn">昨日</x-button>
          <a v-if="loadingStatus" class="datePicker"><i class="iconfont icon-rilicalendar107"></i></a>
          <datetime v-else v-model="choosenDate" :start-date="startDate" :end-date="endDate" @on-confirm="changeDate(0)" class="datePicker">
            <i class="iconfont icon-rilicalendar107"></i>
          </datetime>
        </div>
        <h2 class="title">
          ¥ <span v-text="formatCurrency(summaryInfo.total)">0</span>元<br/>
          <small>总实际收入：</small>
        </h2>
        <grid :cols="2" style="text-align: center;">
          <grid-item label="营业额：">
            <span class="data">¥ <span v-text="formatCurrency(summaryInfo.turnover)">0</span>元</span>
          </grid-item>
          <grid-item label="赠送金额：">
            <span class="data">¥ <span v-text="formatCurrency(summaryInfo.presentTotal)">0</span>元</span>
          </grid-item>
          <grid-item label="销售数量：">
            <span class="data"><span v-text="summaryInfo.salesNumber">0</span></span>
          </grid-item>
          <grid-item label="赠送数量：">
            <span class="data"><span v-text="summaryInfo.presentNumber">0</span></span>
          </grid-item>
        </grid>
      </div>
    </card>
    <group title="酒水分类统计（双指操作放大缩小，按住左右滑动，长按显示标签）：">
      <canvas height="260" class="noselect" ref="vChart"></canvas>
      <div style="height: 30px;"></div>
    </group>
    <group title="酒水销售明细：">
      <x-table :cell-bordered="false">
        <thead>
        <tr style="background-color: #F7F7F7">
          <th width="26%">菜品名称</th>
          <th width="22%">销售数量</th>
          <th width="22%">赠送数量</th>
          <th width="30%">实际收入</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="(item,index) in summaryInfo.detail" :key="index">
          <td v-text="item.goodName"></td>
          <td v-text="item.salesNumber"></td>
          <td v-text="item.presentNumber"></td>
          <td v-text="'¥ ' + formatCurrency(item.total) + '元'"></td>
        </tr>
        <tr v-if="JSON.stringify(summaryInfo) != '{}' && summaryInfo.detail.length <= 0">
          <td colspan="4">
            <div class="listNoItem">暂无酒水销售明细</div>
          </td>
        </tr>
        </tbody>
      </x-table>
      <br/>
    </group>
  </div>
</template>

<script>
  import F2 from '@antv/f2/build/f2-all.js'
  import {XButton, Card, Grid, GridItem, Group, Datetime, GroupTitle, XTable, numberComma, dateFormat } from 'vux'
  import {getSalesSummary} from "../../api";
  import {message,toDecimal2} from "../../common/util";

  export default {
    name:'salesSummary',
    data(){
      return{
        showHeaderBack:this.GLOBAL.showHeaderBack,
        loadingStatus:true,
        choosenDate:dateFormat(new Date(), 'YYYY-MM-DD'),
        startDate:'2019-01-01',
        endDate:dateFormat(new Date(), 'YYYY-MM-DD'),
        summaryInfo:{},
        chartData:[],
        chartData_name:[],
        chart:{}
      }
    },
    components:{
      XButton,
      Card,
      Grid,
      GridItem,
      Group,
      Datetime,
      GroupTitle,
      XTable
    },
    computed:{
    },
    methods:{
      goToPage(){
        this.$router.push({path:'/'})
      },
      formatCurrency(number){
        return numberComma(toDecimal2(number))
      },
      changeDate(value){
        console.log(value)
        switch (value) {
          case 1:this.choosenDate = dateFormat(new Date(), 'YYYY-MM-DD');break;
          case 2:this.choosenDate = dateFormat(new Date().setDate(new Date().getDate()-1), 'YYYY-MM-DD');break;
          default: break;
        }
        console.log(this.choosenDate)
        this.changeChartData()
      },
      refreshPage(params){
        this.loadingStatus = true
        this.chartData = []
        getSalesSummary(this.choosenDate).then((res)=>{
          if(res.status == 'success'){
            this.summaryInfo = res.data
            this.chartData = this.summaryInfo.catagery
          }else if(res.status == 'error') {
            message({message:res.msg,type:'error'})
            console.log('getSalesSummary error info:', res.msg)
          }
          if(params && params.callback && typeof params.callback == 'function')params.callback(res.status)
        }).catch((err)=>{console.log('getSalesSummary catch info:',err)})
      },
      initChart(){
        this.chartData_name = []
        const windowWidth = window.innerWidth
        /*const windowHeight = window.innerHeight
        let itemNum = windowWidth < windowHeight?5:10
        for(let i = this.chartData.length - 1; i >= this.chartData.length - itemNum; i--){
          this.chartData_name.push(this.chartData[i].catageryName)
        }
        this.chartData_name.reverse()*/
        this.chart = new F2.Chart({
          id: this.$refs.vChart,
          width: windowWidth,
          pixelRatio: window.devicePixelRatio,
          height: 320,
          padding: ['auto', 'auto', 90, 'auto']
        });
        this.chart.source(this.chartData, {
          total: {tickCount: 5}/*,
          catageryName: {
            values: this.chartData_name
          }*/
        })
        this.chart.axis('catageryName', {
          label: {
            rotate: Math.PI / 3,
            textAlign: 'start',
            textBaseline: 'middle'
          }
        });
        this.chart.tooltip({
          showItemMarker: false,
          onShow: function onShow(ev) {
            var items = ev.items;
            items[0].name = null;
            items[0].name = items[0].title;
            items[0].value = '¥ ' + items[0].value + '元';
          }
        })
        this.chart.interval().position('catageryName*total');
        // 定义进度条
        this.chart.scrollBar({
          mode: 'x',
          xStyle: {
            backgroundColor: '#e8e8e8',
            fillerColor: '#808080',
            offsetY: -2
          }
        });
        this.chart.interaction('pan').interaction('pinch');
        this.chart.render();
      },
      changeChartData(){
        this.refreshPage({callback:(status)=>{
            if(status == 'success') this.reInitChart()
            this.loadingStatus = false
          }})
      },
      reInitChart(){
        this.chart.destroy()
        this.initChart()
      }
    },
    mounted(){
      this.refreshPage({callback:(status)=>{
          if(status == 'success'){
            this.initChart()
            window.addEventListener('resize', this.reInitChart)
          }
          this.loadingStatus = false
          this.$store.commit('updateLoadingStatus',{isLoading:false})
        }})
    },
    beforeDestroy () {
      window.removeEventListener('resize', this.reInitChart)
      this.chart.destroy()
    }
  }
</script>

<style lang="scss">
  .salesSummary{
    .gridDisplay{
      .filterArea{
        &.dateFilter{
          margin-bottom: 0.5rem;
          .datePicker{
            float: right;padding: 0;
            &.weui-cell:before{border-top: none;}
            i{font-size: 2rem;color:#535353;}
          }
        }
        .filterItem{margin-top: 0.5rem;}
      }
      h2.title{
        line-height: 1.8rem;color: #636363;font-size:2rem;text-align: center;margin: 1rem 0;
        small{font-size:1rem;color: #999999;}
      }
      .data{display: inline-block;height:1.5rem;}
    }
    .noselect {
      -webkit-touch-callout: none; /* iOS Safari */
      -webkit-user-select: none; /* Safari */
      -khtml-user-select: none; /* Konqueror HTML */
      -moz-user-select: none; /* Firefox */
      -ms-user-select: none; /* Internet Explorer/Edge */
      user-select: none; /* Non-prefixed version, currently
                                  supported by Chrome and Opera */
    }
  }
</style>
